from sqlalchemy import select

from dc_shop.core.models.dto import PaymentDetailsDTO
from dc_shop.core.models.enums.currency import Currency
from dc_shop.database.converters.payment_details import convert_db_model_to_payment_details_dto
from dc_shop.database.exception_mapper import exception_mapper
from dc_shop.database.models import PaymentDetails
from dc_shop.database.repositories.base import SQLAlchemyRepo


class PaymentMethodRepoImpl(SQLAlchemyRepo):
    @exception_mapper
    async def get_payment_method_by_id(self, payment_method_id: int) -> PaymentDetailsDTO:
        """Получаем метод оплаты по id"""

        payment_method: PaymentDetails | None = await self._session.scalar(
            select(PaymentDetails).where(
                PaymentDetails.id == payment_method_id,
            )
        )
        payment_method_dto = convert_db_model_to_payment_details_dto(payment_method)

        return payment_method_dto

    @exception_mapper
    async def get_payment_method_by_currency(self, currency: Currency) -> PaymentDetails:
        """Получаем метод оплаты по валюте"""

        payment_method: PaymentDetails | None = await self._session.scalar(
            select(PaymentDetails).where(
                PaymentDetails.currency == currency,
            )
        )

        return payment_method

    @exception_mapper
    async def get_payment_methods(self, is_self_delivery: bool = False) -> list[PaymentDetailsDTO]:
        """
        Получаем все методы оплаты
        @param is_self_delivery: Получить методы, доступные при самовывозе
        """

        query = select(PaymentDetails)
        if is_self_delivery:
            query = query.where(PaymentDetails.available_for_self_pickup)

        res = await self._session.scalars(query)
        payment_methods: list[PaymentDetails] = list(res)

        payment_methods_dtos = [
            convert_db_model_to_payment_details_dto(payment_method) for payment_method in payment_methods
        ]

        return payment_methods_dtos
